import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "E生平安·百万医"

    # 生产产品信息
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": [""],
                # 恶性肿瘤保险金
                "cancerMedical": [""],
                # 亚洲特定疾病保险金
                "AsiaMedical": [""],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["A"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": ["1000000"],
                # 恶性肿瘤保险金
                "cancerMedical": [""],
                # 亚洲特定疾病保险金
                "AsiaMedical": [""],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["B"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": [""],
                # 恶性肿瘤保险金
                "cancerMedical": ["200000"],
                # 亚洲特定疾病保险金
                "AsiaMedical": [""],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["C"]

            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": ["1000000"],
                # 恶性肿瘤保险金
                "cancerMedical": ["200000"],
                # 亚洲特定疾病保险金
                "AsiaMedical": [""],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["D"]

            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": [""],
                # 恶性肿瘤保险金
                "cancerMedical": ["200000"],
                # 亚洲特定疾病保险金
                "AsiaMedical": ["6000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["E"]
            },
            "planF": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": [""],
                # 恶性肿瘤保险金
                "cancerMedical": [""],
                # 亚洲特定疾病保险金
                "AsiaMedical": ["6000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["F"]
            },
            "planG": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": [""],
                # 恶性肿瘤保险金
                "cancerMedical": ["200000"],
                # 亚洲特定疾病保险金
                "AsiaMedical": ["6000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["G"]
            },
            "planH": {
                # 年龄段
                "year": [str(i) for i in range(0, 61)],
                # 有无社保
                "socialSec": ["Y", "N"],
                # 一般医疗保险金
                "generalMedical": ["2000000"],
                # 特定疾病保险金
                "specialMedical": ["2000000"],
                # 质子重离子保险金
                "extSerious": ["1000000"],
                # 恶性肿瘤保险金
                "cancerMedical": ["200000"],
                # 亚洲特定疾病保险金
                "AsiaMedical": ["6000000"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 计划
                "plan": ["H"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["generalMedical"],
                             plan[k]["specialMedical"], plan[k]["extSerious"], plan[k]["cancerMedical"],
                             plan[k]["AsiaMedical"], plan[k]["expire"], plan[k]["payType"], plan[k]["plan"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"flowId": "F0N3cZedOquWEB1P",
                "planPackage": {"packageCode": "PK00027569", "marketProductCode": "MP03000679", "packageType": "01"},
                "insurantNum": [{"personNum": "1", "subjectType": "02"}], "applyPeriod": {"term": 12, "termUnit": "M"},
                "effectDate": {"beginDate": "2020-03-18", "endDate": "2021-03-17", "birthDay": ""+str(2020-int(dt["year"]))+"-01-01"},
                "addDays": "", "security": ""+"1" if dt["socialSec"] =="Y" else "2"+""}

        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "处理成功" in r.text:
            price_list = r.json()["quoteResult"]
            if dt["plan"] == "A":
                price = Helper.decimalParse(price_list[0]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
            elif dt["plan"] == "B":
                price = Helper.decimalParse(price_list[1]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
            elif dt["plan"] == "C":
                price = Helper.decimalParse(price_list[2]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
            elif dt["plan"] == "D":
                price = Helper.decimalParse(price_list[3]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
            elif dt["plan"] == "E":
                price = Helper.decimalParse(price_list[4]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
            elif dt["plan"] == "F":
                price = Helper.decimalParse(price_list[5]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
            elif dt["plan"] == "G":
                price = Helper.decimalParse(price_list[6]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
            else:
                price = Helper.decimalParse(price_list[7]["orginalPremium"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print(data)
                self.mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            print(dt)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)

